package com.saodisheng.service.impl;


import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.saodisheng.model.User;
import com.saodisheng.service.UserFriendService;
import com.saodisheng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * description:
 *
 * @author 扫地生_saodisheng
 * @date 2021/12/29
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserFriendService userFriendService;

    final String myFollowCacheName = "myFollowList";
    final String myFansCacheName = "myFansList";
    final String followAndFansTotalCacheName = "followAndFansTotal";
    private final User userDao = new User().dao();
    int pageSize = 12;


    @Override
    public User getUserById(int userId) {
        User account = userDao.findFirst("select * from user where id=?", userId);
        return account;
    }


    @Override
    public boolean isFollowUser(int userId, int friendId) {
        User user = userDao.findFirst("select * from friend where userId=? and friendId=?", userId, friendId);
        //如果记录已经存在，则表示已经关注
        if (user != null) {
            return true;
        }
        return false;
    }

    @Override
    public Ret followUser(int userId, int friendId) {
        User user = userDao.findFirst("select * from friend where userId=? and friendId=?", userId, friendId);

        //如果记录已经存在，则表示取消关注操作
        if (user != null) {
            int r = Db.update("delete from friend where userId=? and friendId=?", userId, friendId);
            if (r>0) {
                return Ret.ok("msg", "已取消关注");
            }

            return Ret.fail("msg", "取消关注失败");
        }

        //如果记录不存在，则插入记录
        int r = Db.update("insert into friend "
                + "(userId, friendId, createAt) values (?,?,?)", userId, friendId, new Date());
        if (r>0) {
            return Ret.ok("msg", "已关注");
        }

        return Ret.fail("msg", "关注失败");
    }

    @Override
    public List<User> getFollowUser(int userId) {
        List<User> follows = userDao.find("select f.*,u.avatar,u.nickName,u.signature from friend f join user u on f.friendId=u.id and f.userId=?",userId);
        return follows;
    }

    @Override
    public List<User> getFans(int userId) {
        List<User> fans = userDao.find("select f.*,u.avatar,u.nickName,u.signature from friend f join user u on f.userId=u.id and f.friendId=?",userId);
        return fans;
    }


    @Override
    public int getFriendRelation(int userId, int friendId) {
        // userId 与 friendId 相同
        if (userId == friendId) {
            return -1;
        }

        List<Record> list = Db.find(
                "select userId, friendId from friend where userId= ? and friendId= ? union all " +
                        "select userId, friendId from friend where userId= ? and friendId= ?",
                userId, friendId, friendId, userId);
        // 两个账号无任何关系
        if (list.size() == 0) {
            return 0;
        }
        if (list.size() == 1) {
            // userId 关注了 friendId
            if (list.get(0).getInt("userId") == userId) {
                return 1;
            } else {
                // friendId 关注了 userId
                return 2;
            }
        }
        if (list.size() == 2) {
            // userId 与 friendId 互相关注
            return 3;
        }

        throw new RuntimeException("不可能存在的第五种关系，正常情况下该异常永远不可能抛出");
    }

    @Override
    public int[] getFollowAndFansCount(int userId) {
        // 两种 sql 都可以实现功能，注意这里要使用 union all，需要避免去重
        String sql = "select count(*) from friend f1 where userId = ? union all " +
                "select count(*) from friend f2 where friendId = ? ";
        List<Long> list = Db.query(sql, userId, userId);
        return new int[]{list.get(0).intValue(), list.get(1).intValue()};
    }

    @Override
    public void clearCache(int accountId, int friendId) {
        CacheKit.remove(myFollowCacheName, accountId);
        CacheKit.remove(myFollowCacheName, friendId);

        CacheKit.remove(myFansCacheName, accountId);
        CacheKit.remove(myFansCacheName, friendId);

        CacheKit.remove(followAndFansTotalCacheName, accountId);
        CacheKit.remove(followAndFansTotalCacheName, friendId);

        userFriendService.clearCache(accountId);
        userFriendService.clearCache(friendId);
    }
}
